# -*- coding:utf-8 -*-
import argparse
import traceback

from flask import Flask, render_template, make_response, send_from_directory
import flask_restful as restful
from flask_restful import reqparse

from pyecharts import Bar
from pyecharts.constants import DEFAULT_HOST
from pyecharts.utils import json_dumps

from common.log import init, info, warn, debug, error
from common.utils import byteify

DEFAULT_LOG_PATH = 'server.log'

app = Flask('WebChart')
@app.after_request
def after_request(response):
    # 设置Access-Control-Allow-Origin实现跨域访问 
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

api = restful.Api(app)

@api.representation('text/html')
def output_html(data, code, headers=None):
    # 设置响应为 html
    resp = make_response(data, code)
    resp.headers.extend(headers or {})
    return resp

@app.route('/echarts/<path:path>')
def send_js(path):
    return send_from_directory('static', path)

class BarRestAPI(restful.Resource):
    """
    Bar chart html rest api
    """
    @staticmethod
    def echart_bar(title, sub_title, bar_name, x_axis_list, y_axis_list):
        bar = Bar(title, sub_title)
        bar.add(bar_name, x_axis_list, y_axis_list)
        return bar

    def get(self):
        """
        Get a bar chart with html format.
        :param :
        :return: html code.
        """
        res = None
        status_code = 200
        try:
            _bar = self.echart_bar(title="我的第一个图表", sub_title="这里是副标题",
                                    bar_name="服装",
                                    x_axis_list=["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
                                    y_axis_list=[5, 20, 36, 10, 75, 90])
            res = render_template('pyecharts.html',
                           chart_id=_bar.chart_id,
                           host='/echarts',
                           my_width="100%",
                           my_height=600,
                           my_option=json_dumps(_bar.options),
                           script_list=_bar.get_js_dependencies())
        except Exception as ex:
            error(traceback.format_exc())
            error(ex)
            res = str(ex)
            status_code = 403

        return res, status_code

    @staticmethod
    def _reqparse():
        # curl -X POST -H "Content-Type:application/json"
        # -d '{"title":"a","sub_title":"b","bar_name":"c",
        # "x_axis":[1,2,5],"y_axis":[2.2,4.5]}'
        # http://localhost:5000/bar
        parser = reqparse.RequestParser()
        parser.add_argument("title", type=str)
        parser.add_argument("sub_title", type=str)
        parser.add_argument("bar_name", type=str)
        parser.add_argument("x_axis", type=str, action='append')
        parser.add_argument("y_axis", type=str, action='append')
        args = parser.parse_args()
        return args

    def post(self):
        """
        Post a bar chart data to server.
        :return: access url
        """
        args = self._reqparse()
        debug("title:%s" % (args.title))
        debug("sub title:%s" % (args.sub_title))
        debug("bar name:%s" % (args.bar_name))
        debug("x axis:%s" % (args.x_axis))
        debug("y axis:%s" % (args.y_axis))
        
api.add_resource(BarRestAPI, '/bar')
        
def _str2bool(v):
    return v.lower() in ("yes", "true", "t", "ok", "1")
        
def argument_parser():
    parser = argparse.ArgumentParser(description="Aliyun ECS Operation CLI.")

    parser.add_argument("-l", "--log-path", action="store", type=str, dest="log_path",
                        help="Server log path.", required=False, default=DEFAULT_LOG_PATH)
    parser.add_argument("-p", "--port", action="store", type=int, dest="port",
                        help="Server port.", required=False, default=5000)
    parser.add_argument("-d", "--debug", action="store", type=_str2bool, dest="debug",
                        help="Enable service debug information.", required=False, default=False)

    return parser.parse_args()

if __name__ == '__main__':
    args = argument_parser()
    init(logpath=args.log_path, log_level='DEBUG' if args.debug else 'INFO')
    app.run(host='0.0.0.0', debug=args.debug)

